<template>
  <div class="params-page">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <span>选择商品分类：</span>
      <el-cascader
        :options="cataList"
        v-model="selectdCateKeys"
        :props="{ expandTrigger: 'hover', checkStrictly: true, ...cateProps }"
        @change="handleChange"
      >
      </el-cascader>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            @click="isDialogVisible('添加')"
            size="mini"
            :disabled="isBtnDisabled"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button
                  type="primary"
                  @click="isDialogVisible('修改', row.attr_id)"
                  icon="el-icon-edit"
                  size="mini"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  @click="removeParams(row.attr_id)"
                  icon="el-icon-delete"
                  size="mini"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            @click="isDialogVisible('添加')"
            size="mini"
            :disabled="isBtnDisabled"
            >添加属性</el-button
          >
          <el-table :data="onlyTableData" border stripe>
            <el-table-column label="属性名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="isDialogVisible('修改', row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  @click="removeParams(row.attr_id)"
                  icon="el-icon-delete"
                  size="mini"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog
      :title="type + titleText"
      :visible.sync="dialogVisible"
      width="50%"
      @close="dialogClosed"
    >
      <el-form
        :model="form"
        :rules="fromRules"
        ref="formRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="form.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="changeParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  addManyCategoriesApi,
  delManyCategoriesApi,
  editManyCategoriesApi,
  getAttributesInfoApi,
  getCategoriesAllApi,
  getManyCategoriesApi,
} from "@/api/params";

export default {
  name: "paramsPage",
  data() {
    return {
      cataList: [],
      // 级联选择框的配置对象
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // 级联选择框双向绑定的数组
      selectdCateKeys: [],
      // 被激活的页签的名称
      activeName: "many",
      // 动态参数数据
      manyTableData: [],
      // 静态属性数据
      onlyTableData: [],
      // 控制添加对话框的显示和隐藏
      dialogVisible: false,
      cId: "",
      // 添加/修改参数的表单数据对象
      form: {
        attr_name: "",
      },
      type: "添加",
      fromRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getCategoriesList();
  },
  methods: {
    async getCategoriesList() {
      const res = await getCategoriesAllApi();
      // console.log(res);
      if (res.meta.status == 200) {
        this.cataList = res.data;
      } else {
        this.$message.error("获取商品分类失败!");
      }
    },
    handleChange() {
      this.getParamsData();
    },
    async getParamsData() {
      // 证明选中的不是三级分类
      if (this.selectdCateKeys.length !== 3) {
        this.selectdCateKeys = [];
        this.manyTableData = [];
        this.onlyTableData = [];
        return;
      }
      const res = await getAttributesInfoApi(this.cateId, {
        sel: this.activeName,
      });
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数列表失败!");
      }
      // 获取Tag的数据分割为数组
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        // 控制文本框的显示和隐藏
        item.inputVisible = false;
        item.inputValue = "";
      });
      if (this.activeName === "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTableData = res.data;
      }
      // console.log(res.data);
    },
    handleTabClick() {
      console.log(this.activeName);
      this.getParamsData();
    },
    async isDialogVisible(type, id) {
      this.dialogVisible = true;
      this.cId = id;
      this.type = type;
      if (this.type === "修改") {
        const res = await getManyCategoriesApi(this.cateId, id, {
          attr_sel: this.activeName,
        });
        this.form.attr_name = res.data.attr_name;
        this.form.attr_id = res.data.attr_id;
      }
    },
    dialogClosed() {
      this.$refs.formRef.resetFields();
      this.form.attr_name = "";
    },
    async changeParams() {
      await this.$refs.formRef.validate();
      if (this.type === "添加") {
        const res = await addManyCategoriesApi(this.cateId, {
          attr_name: this.form.attr_name,
          attr_sel: this.activeName,
        });
        if (res.meta.status === 201) {
          this.$message.success("添加成功");
          this.dialogVisible = false;
        } else {
          this.$message.error("添加失败");
        }
      } else if (this.type === "修改") {
        const res = await editManyCategoriesApi(
          this.cateId,
          this.form.attr_id,
          {
            attr_name: this.form.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status === 200) {
          this.$message.success("修改成功");
          this.dialogVisible = false;
        } else {
          this.$message.error("修改失败");
        }
      }
      this.getParamsData();
      this.dialogVisible = false;
    },
    async removeParams(id) {
      const resConfrm = await this.$confirm(
        "此操作将永久删除, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (resConfrm !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const res = await delManyCategoriesApi(this.cateId, id);
      if (res.meta.status === 200) {
        this.$message.success("删除成功");
      } else {
        this.$message.error(res.meta.msg);
      }
      this.getParamsData();
    },
  },
  computed: {
    cateId() {
      if (this.selectdCateKeys.length === 3) {
        return this.selectdCateKeys[2];
      }
      return null;
    },
    // 如果按钮需要被禁用.则返回true,否则返回fasle
    isBtnDisabled() {
      if (this.selectdCateKeys.length !== 3) {
        return true;
      } else {
        return false;
      }
    },
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      } else {
        return "静态参数";
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.el-breadcrumb {
  margin-bottom: 15px;
}
.el-alert {
  margin-bottom: 15px;
}
.el-table {
  margin-top: 15px;
}
</style>
